<?php
namespace App\Admin\Controllers\Tool;

use App\Models\Basics\SysCountry;
use App\Models\Delivery\FBADelivery;
use App\Models\Delivery\OSDelivery;
use App\Models\Delivery\OSDeliveryBox;
use App\Models\Delivery\OSDeliveryBoxDetail;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductSku;
use App\Models\SalesReport\DailySv;
use Encore\Admin\Controllers\AdminController;
use Symfony\Component\HttpFoundation\StreamedResponse;

class HelperController extends AdminController{

    protected $title = '辅助工具';

    protected function tool()
    {
//        self::_FBACode();
    }

    public static function _FBACode(){
        $query = \App\Models\OverSeasOut\RemovaleDelivery::query();
        $head = ['发货单号','亚马逊账号','发货站点','发货国家','发货地址','发货时间','创建时间'];
        set_time_limit(0);
        $response = new StreamedResponse(null, 200, [
            'Content-Type'        => 'text/csv;charset=utf-8',
            'Content-Disposition' => 'attachment;filename="分国家库存.csv"',
        ]);
        $response->setCallback(function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->orderBy('id')->chunk(200, function ($re) use ($fp){
                foreach ($re as $row){
                    $temp = [
                        $row->delivery_no,
                        $row->account->account ?? '',
                        $row->area->area ?? '',
                        $row->country->country ?? '',
                        $row->d_address,
                        $row->delivered_at,
                        $row->created_at,
                    ];
                    fputcsv($fp, $temp);
                }
            });
            fclose($fp);
        });
        $response->send();
        exit(0);
    }

    public static function _inventory(){
        $query = DailySv::query()->whereIn('country_id',[1,2,3,4])->whereIn('classify_id',[212,217,216,209,210,205]);
        $head = ['国家','产品','SKU','季节性','品类','FBA在库','FBA在途','国内在库','国内在途','海外仓在库','海外仓在途'];
        set_time_limit(0);
        $response = new StreamedResponse(null, 200, [
            'Content-Type'        => 'text/csv;charset=utf-8',
            'Content-Disposition' => 'attachment;filename="分国家库存.csv"',
        ]);
        $response->setCallback(function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $data = [];
            $query->orderBy('id','DESC')->chunk(500, function ($re) use ($fp,&$data){
                foreach ($re as $row) {
                    $data[$row->country_id][$row->classify_id][] = [
                        'psku_id' => $row->psku_id,
                        'fba_instant_num' => $row->fba_instant_num,
                        'fba_transit_num' => $row->fba_transit_num,
                        'cn_instant_num' => $row->cn_instant_num,
                        'cn_transit_num' => $row->cn_transit_num,
                        'os_instant_num' => $row->os_instant_num,
                        'os_transit_num' => $row->os_transit_num,
                    ];
                }
            });
            foreach ($data as $countryId => $_dataTemp) {
                $country = SysCountry::getCountryById($countryId);
                foreach ($_dataTemp as $classifyId => $_data){
                    $ttl_fba_instant_num = 0;
                    $ttl_fba_transit_num = 0;
                    $ttl_cn_instant_num = 0;
                    $ttl_cn_transit_num = 0;
                    $ttl_os_instant_num = 0;
                    $ttl_os_transit_num = 0;
                    foreach ($_data as $row) {
                        $ttl_fba_instant_num += $row['fba_instant_num'];
                        $ttl_fba_transit_num += $row['fba_transit_num'];
                        $ttl_cn_instant_num += $row['cn_instant_num'];
                        $ttl_cn_transit_num += $row['cn_transit_num'];
                        $ttl_os_instant_num += $row['os_instant_num'];
                        $ttl_os_transit_num += $row['os_transit_num'];
                    }
                    $title = ProductClassify::getTitleById($classifyId);
                    $_season = ProductClassify::getSeasonById($classifyId);
                    $season = ProductClassify::$_season[$_season];
                    $tempTTL = [
                        $country,
                        $title,
                        'TTL',
                        '',
                        '',
                        $ttl_fba_instant_num,
                        $ttl_fba_transit_num,
                        $ttl_cn_instant_num,
                        $ttl_cn_transit_num,
                        $ttl_os_instant_num,
                        $ttl_os_transit_num,
                    ];
                    fputcsv($fp, $tempTTL);
                    foreach ($_data as $row) {
                        $temp = [
                            '',
                            '',
                            ProductSku::getValueById($row['psku_id'],'psku_code'),
                            $season,
                            $title,
                            $row['fba_instant_num'],
                            $row['fba_transit_num'],
                            $row['cn_instant_num'],
                            $row['cn_transit_num'],
                            $row['os_instant_num'],
                            $row['os_transit_num'],
                        ];
                        fputcsv($fp, $temp);
                    }
                }
            }
            fclose($fp);
        });
        $response->send();
        exit(0);
    }

    public static function _boxDownload(){
        $head = ['发货单','站点', 'SKU', '长', '宽', '高', '箱率', '箱重'];
        $response = new StreamedResponse(null, 200, [
            'Content-Type'        => 'text/csv;charset=utf-8',
            'Content-Disposition' => 'attachment;filename="箱规.csv"',
        ]);
        $query = OSDeliveryBoxDetail::query();
        $response->setCallback(function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $arr = [];
            $query->orderBy('id')->chunk(200, function ($re) use ($fp,$arr){
                foreach ($re as $row){
                    $value = $row->delivery_no.'_'.$row->sku;
                    if(!in_array($value,$arr)){
                        $arr[] = $value;
                    }else{
                        continue;
                    }
                    $box = OSDeliveryBox::query()->find($row->delivery_box_id);
                    if(!$box){
                        continue;
                    }
                    $d = OSDelivery::query()->where('delivery_no',$row->delivery_no)->first();
                    if(!$d){
                        continue;
                    }
                    $temp = [
                        $row->delivery_no,
                        $d->area->area ?? '',
                        $row->sku,
                        $box->long,
                        $box->wide,
                        $box->high,
                        $row->num,
                        $box->weight,
                    ];
                    fputcsv($fp, $temp);
                }
            });
            fclose($fp);
        });
        $response->send();
        exit(0);
    }
}
